package cn.shenlong.portal.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.shenlong.common.Constants;
import cn.shenlong.common.Page;
import cn.shenlong.common.Pagination;
import cn.shenlong.portal.domain.Member;
import cn.shenlong.portal.domain.User;
import cn.shenlong.portal.service.MemberService;
import cn.shenlong.util.UploadUtil;

@Controller
@RequestMapping("/member/admin")
public class MemberAController {
	@Autowired
	private MemberService memberService;
	
	@RequestMapping("/index")
	public String index(){
		return "/server/member/index";
	}
	
	@RequestMapping("/list")
	public String main(Member member,String searchProperty, String searchValue,Integer pageSize, Integer pageNumber,ModelMap model){
		if(pageSize==null){
			pageSize = 20;
		}
		if(pageNumber==null){
			pageNumber = 1;
		}
		
		Map<String,Object> parm = new HashMap<String,Object>();
		if(searchProperty!=null){
			parm.put(searchProperty, searchValue);
			model.put("searchValue", searchValue);
			parm.put("searchProperty", searchProperty);
			model.put("searchProperty", searchProperty);
		}
		Page p = memberService.findPageByParm(parm, pageNumber, pageSize);
		model.put("page", p);
		
		return "/server/member/list";
	}
	
	@RequestMapping("/addMember")
	public String addMember(){
		return "/server/member/add";
	}
	
	@RequestMapping("/showMember")
	public String showMember(Long memberId,ModelMap model){		
		Member member = this.memberService.findMemberByMemberId(memberId);
		model.put("member", member);
		return "/server/member/show";
	}
	
	@RequestMapping("/saveMember")
	public String saveMember(Member member,ModelMap model,MultipartHttpServletRequest request){
		if(member == null || member.getMemberId() == null){ //新增
			try {				
				Long count = memberService.findMemberCountByName(member.getLoginName());
				if (count.longValue() == 0) {
					List<Map<String, Object>> resultList = UploadUtil.uploadImage(request, Constants.COMPANY_IMG_URI);
					if(!resultList.isEmpty()){
						member.setImgUrl(resultList.get(0).get("imagePath").toString());					
					}
					member.setDataflg(1);
					memberService.save(member);
					if(member != null) model.put("msg", "success");
					return "redirect:list.html";
				} else {
					model.put("msg", "failed");
					return addMember();
				}
			} catch (Exception e) {
				model.put("msg", "failed");
			}
			return addMember();
		} else {//编辑
			Member origionMember = memberService.findMemberByMemberId(member.getMemberId());
			try {
				List<Map<String, Object>> resultList = UploadUtil.uploadImage(request, Constants.COMPANY_IMG_URI);
				if(!resultList.isEmpty()){//有上传图片
					//删除原来的图片
					UploadUtil.deleteForUrl(origionMember.getImgUrl());
					
					//设置新的路径
					origionMember.setImgUrl(resultList.get(0).get("imagePath").toString());
				}
				member = memberService.updateMember(member);
				if(member != null) model.put("msg", "success");
				return "redirect:list.html";
			} catch (Exception e) {
				model.put("msg", "failed");
				model.put("member", member);
			}
			return this.editMember(member.getMemberId(), model);
		}
		
	}
	
	@RequestMapping("/editMember")
	public String editMember(Long memberId,ModelMap model){
		if(model == null || model.get("member") == null){			
			Member member = this.memberService.findMemberByMemberId(memberId);
			model.put("member", member);
		}
		return "/server/member/edit";
	}
	
	@RequestMapping("/deleteMember")
    @ResponseBody
	public Map<String ,Object> deleteMember(Long memberId,String memberIdStr,HttpServletRequest request, HttpServletResponse response,ModelMap model){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if (memberId == null) {				
				String[] tmp = memberIdStr.split(",");
				Long[] memberIds = new Long[tmp.length];
				for (int i = 0; i < tmp.length; i++) {
					memberIds[i] = Long.parseLong(tmp[i]);
				}
				memberService.deleteMember(memberIds);
			}else{
				memberService.deleteMember(new Long[]{memberId});
			}
			resultMap.put("result", "删除成功！");	
		}catch (Exception e) {
			e.printStackTrace();
			resultMap.put("result","删除失败！原因："+e.toString());
		}
		return resultMap;
	}
	
	/**
	 * ajax上传图片
	 */
	@RequestMapping("/uploadImage")
    @ResponseBody
	public Map<String,Object> uploadImage(HttpServletRequest request, HttpServletResponse response, ModelMap model){
		Map<String,Object>  resultMap = new HashMap<String,Object>();
		try{
			List<Map<String, Object>> resultList = UploadUtil.uploadImage(request,Constants.COMPANY_IMG_URI);	
			resultMap.put("path", resultList.get(0).get("imagePath"));
			resultMap.put("result", true);
		}catch (Exception e) {
			e.printStackTrace();
			resultMap.put("result", false);
		}		
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/ajaxLoginName")
	public Map<String, Object> ajaxLoginName(String loginName, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (StringUtil.isBlank(loginName)) {
			resultMap.put("msg", "参数为空");
			return resultMap;
		}
		Long count = memberService.findMemberCountByName(loginName);
		if (count.longValue() == 0) {
			resultMap.put("msg", "true");
		} else {
			resultMap.put("msg", "用户已存在，请重新填写用户名");
		}

		return resultMap;

	}
}
